package com.moorror.codegenvel.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2024/4/10 23:59
 */
public class ExceptionMessageUtil {

    public static String exceptionTopLog(Exception ex) {
        if (null == ex) {
            return "";
        }
        StackTraceElement[] stacks = ex.getStackTrace();
        if (null == stacks || 0 == stacks.length) {
            return String.format("cause:%s", ex.getClass());
        }
        List<StackElementDesc> stackElementDescs = Lists.newArrayList();
        for (StackTraceElement ele : stacks) {
            if (StringUtils.isNotBlank(ele.getClassName()) && ele.getClassName().startsWith("")) {
                stackElementDescs.add(StackElementDesc.of(ele.getClassName(), ele.getMethodName(), ele.getLineNumber()));
            }
        }
        return String.format("cause:%serrorStack:%s", ex.getClass(), JSON.toJSONString(stackElementDescs));
    }


    @Data
    private static class StackElementDesc {
        private String className;
        private String methodName;
        private int lineNumber;

        public static StackElementDesc of(String className, String methodName, int lineNumber) {
            StackElementDesc stackELementDesc = new StackElementDesc();
            stackELementDesc.setClassName(className);
            stackELementDesc.setMethodName(methodName);
            stackELementDesc.setLineNumber(lineNumber);
            return stackELementDesc;
        }
    }
}
